<?php
/**
 * Library of functions to add SimpleLTI activities using a filter.
 * 
 * 
 * @author Jordi Piguillem
 * 
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package basiclti
 * 
 */

global $CFG;

require_once('filterlib.php');
require_once($CFG->dirroot.'/mod/basiclti/locallib.php');

/**
 * This functions replaces text that match with a LTI activity by
 * the activity.
 * 
 * @param int $courseid 			course id
 * @param string $text 				text to be filtered
 * 
 */
function basiclti_filter($courseid, $text) {
	global $CFG;
	$search = '/\[LTI:\ url=(?<url>(.*))\]/';
	if (preg_match($search, $text, $res)){
		$secret = null;
		$url = $res['url'];
		$search = '/\[LTI:\ url=(?<url>(.*)),\ secret=(?<secret>(.*))\]/';
		if (preg_match($search, $text, $res)){
			$secret = $res['secret'];
			$url = $res['url'];
		} else if (!$CFG->filter_basiclti_password){
			if($server = basiclti_filter_get_server_by_url($url)){
				$secret = $server->password;
			}
		}
		if (isset($secret)){
			$params = basiclti_filter_get_request_params($secret);
			$response = basiclti_request($url, $secret,$params);
			$replamnt = basiclti_filter_format_response($response);
			$search = '/\[LTI:.*\]/';
			$text = preg_replace($search, $replamnt, $text);
		}
	}
	return $text;
}

?>